﻿using AdverseEventReportSystem.BLL;
using AdverseEventReportSystem.BLL.SchedulingSystem;
using AdverseEventReportSystem.Core;
using AdverseEventReportSystem.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace AdverseEventReportSystem.Web.Areas.Scheduling.Controllers
{
    public class SchedulingController : BaseController
    {
        // GET: Scheduling/Scheduling
        public ActionResult Index()
        {
            ViewBag.CurrDepCode = loginUser.CurrDepCode;
            return View();
        }

        /// <summary>
        /// 获取班别列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSchedulingCategoryList()
        {
            OperateResult resultInfo = new OperateResult();
            try
            {
                string departmentCode = WebUtils.GetString("departmentCode");
                DataTable dt = new DataTable();
                SchedulingSystemSoapClient service = new SchedulingSystemSoapClient();
                ResultHelperOfDataTable result = service.GetSchedulingCategoryList(departmentCode);
                if (result.S)
                {
                    var d = result.D.AsEnumerable().Where(x => DataConvert.StrToInt(x["Enabled"]) == 1 && DataConvert.StrToInt(x["IsDel"]) == 0);
                    if (d.Count() > 0)
                    {
                        dt = d.CopyToDataTable<DataRow>();
                    }
                    resultInfo.Body = dt;
                }
                else
                {
                    resultInfo.Result = 0;
                    resultInfo.Body = result.M;
                }
            }
            catch (Exception ex)
            {
                resultInfo.Result = -1;
                resultInfo.Body = ex.Message;
            }

            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 获取排班周期
        /// </summary>
        /// <returns></returns>
        public ActionResult GetScheduleCycleList()
        {
            DataTable dt = new DataTable();
            SchedulingSystemSoapClient service = new SchedulingSystemSoapClient();
            ResultHelperOfDataTable result = service.GetScheduleCycleList();
            if (result.S)
            {
                var d = result.D.AsEnumerable().Where(x => DataConvert.StrToInt(x["Enabled"]) == 1);
                if (d.Count() > 0)
                {
                    dt = d.CopyToDataTable<DataRow>();
                }
            }
            return JsonDate(dt);
        }

        /// <summary>
        /// 获取日期表头
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public ActionResult GetDateTitle(DateTime startDate, DateTime endDate)
        {
            OperateResult resultInfo = new OperateResult();
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Date");
                dt.Columns.Add("DayOfWeek");
                dt.Columns.Add("DateId");

                string[] Day = new string[] { "日", "一", "二", "三", "四", "五", "六" };

                while (startDate <= endDate)
                {
                    dt.Rows.Add(new object[] { startDate.ToString("M/dd"), Day[DataConvert.StrToInt(startDate.DayOfWeek.ToString("d"))], "D_" + startDate.ToString("yyyy-MM-dd") });
                    startDate = startDate.AddDays(1);
                }
                resultInfo.Body = dt;
            }
            catch (Exception ex)
            {
                resultInfo.Result = -1;
                resultInfo.Body = ex.Message;
            }

            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 获取排班模板
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSchedulingTemplateList()
        {
            string departmentCode = WebUtils.GetString("departmentCode");
            DataTable dt = null;
            SchedulingSystemSoapClient service = new SchedulingSystemSoapClient();
            ResultHelperOfDataTable result = service.GetSchedulingTemplateList(departmentCode);
            if (result.S)
            {
                dt = result.D;
            }
            if (dt == null)
            {
                dt = new DataTable();
                dt.Columns.Add("Id");
                dt.Columns.Add("Name");
            }

            DataRow dr = dt.NewRow();
            dr["Id"] = 0;
            dr["Name"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            return JsonDate(dt);
        }

        /// <summary>
        /// 排班列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Search()
        {
            string startDate = WebUtils.GetString("startDate");
            string endDate = WebUtils.GetString("endDate");
            string departmentCode = WebUtils.GetString("departmentCode");
            int templateId = WebUtils.GetInt("templateId");

            SchedulingSystemSoapClient service = new SchedulingSystemSoapClient();
            ResultHelperOfDataTable serviceResult = service.GetSchedulingList(DataConvert.StrToDateTime(startDate, DateTime.Now), DataConvert.StrToDateTime(endDate, DateTime.Now), departmentCode, templateId);
            DataTable dt = new DataTable();
            if (serviceResult.S)
            {
                dt = serviceResult.D;
            }
            var result = new { Rows = dt };
            return JsonDate(result);
        }

        /// <summary>
        /// 保存排班
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(List<AdverseEventReportSystem.BLL.SchedulingSystem.Scheduling> schedulingList, List<SchedulingOvertime> schedulingOvertimeList, string departmentCode)
        {
            OperateResult resultInfo = SchedulingManager.SaveScheduling(schedulingList, schedulingOvertimeList, departmentCode);
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 保存模板
        /// </summary>
        /// <param name="template"></param>
        /// <param name="templateInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveTemplate(SchedulingTemplate template, List<SchedulingTemplateInfo> templateInfo, string departmentCode)
        {
            OperateResult resultInfo = SchedulingManager.SaveTemplate(template, templateInfo, departmentCode);
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 删除排班模板
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DelTemplate(int id)
        {
            OperateResult resultInfo = SchedulingManager.DelTemplate(id);
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 删除排班
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public ActionResult DelScheduling(string startDate, string endDate)
        {
            string departmentCode = WebUtils.GetString("departmentCode");
            OperateResult resultInfo = SchedulingManager.DelScheduling(DataConvert.StrToDateTime(startDate, DateTime.Now), DataConvert.StrToDateTime(endDate, DateTime.Now), departmentCode);
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 打印预览
        /// </summary>
        /// <returns></returns>
        public ActionResult PrintView()
        {
            return View();
        }

        /// <summary>
        /// 打印预览
        /// </summary>
        /// <returns></returns>
        public ActionResult SchedulingPrint()
        {
            return View();
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <returns></returns>
        [LoginAttribute(IsNeed = false)]
        public ActionResult GetSchedulingPrint()
        {
            string startDate = WebUtils.GetString("startDate");
            string endDate = WebUtils.GetString("endDate");
            string departmentCode = WebUtils.GetString("departmentCode");
            int templateId = WebUtils.GetInt("templateId");
            int type = WebUtils.GetInt("type");
            SchedulingSystemSoapClient service = new SchedulingSystemSoapClient();
            ResultHelperOfDataTable serviceResult = service.GetSchedulingPrint(DataConvert.StrToDateTime(startDate, DateTime.Now), DataConvert.StrToDateTime(endDate, DateTime.Now), departmentCode, templateId, type);
            DataTable dt = new DataTable();
            DataTable printDt = new DataTable();
            if (serviceResult.S)
            {
                dt = serviceResult.D;
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataTable leaveDt = new DataTable();
                    OperateResult resultInfo = LeaveManager.GetLeaveInfoList(startDate, endDate, departmentCode);
                    if (resultInfo.Result == 1)
                    {
                        leaveDt = (DataTable)resultInfo.Body;
                    }
                    printDt = dt.Clone();
                    int index = 0;
                    foreach (DataRow item in dt.Rows)
                    {
                        string value = "";
                        if (!string.IsNullOrEmpty(item["CategoryCode"].ToString()) && item["CategoryCode"].ToString() != ",")
                        {
                            string[] codeList = item["CategoryCode"].ToString().Split(',')[0].Split('|');
                            string[] colorList = item["CategoryCode"].ToString().Split(',')[1].Split('|');

                            for (int i = 0; i < codeList.Length; i++)
                            {
                                switch (colorList[i].ToLower())
                                {
                                    case "red":
                                        value += "<font color=#FF0000>" + codeList[i] + "</font> ";
                                        break;
                                    case "gray":
                                        value += "<font color=#BEBEBE>" + codeList[i] + "</font> ";
                                        break;
                                    case "green":
                                        value += "<font color=#00CD00>" + codeList[i] + "</font> ";
                                        break;
                                    case "blue":
                                        value += "<font color=#0000FF>" + codeList[i] + "</font> ";
                                        break;
                                    default:
                                        value += "<font color=#000000>" + codeList[i] + "</font> ";
                                        break;
                                }
                            }
                        }
                        else
                        {
                            if (type == 0)
                            {
                                //休假信息
                                DateTime currDate = DataConvert.StrToDateTime(item["Date"].ToString(), DateTime.Now);
                                var leaveRow = leaveDt.AsEnumerable().Where(r => r.Field<string>("UserId") == item["PersonnelId"].ToString() && r.Field<DateTime>("StartTime").Date <= currDate && r.Field<DateTime>("EndTime").Date >= currDate).Select(r => new { TypeName = r.Field<string>("TypeName"), StartTime = r.Field<DateTime>("StartTime"), EndTime = r.Field<DateTime>("EndTime") }).FirstOrDefault();
                                if (leaveRow != null)
                                {
                                    if (currDate >= leaveRow.StartTime.Date && currDate <= leaveRow.EndTime.Date)
                                    {
                                        value = string.Format("{0}第{1}天", leaveRow.TypeName, WebUtils.DateDiff(WebUtils.DateInterval.Day, leaveRow.StartTime.Date, currDate.Date) + 1);
                                    }
                                }
                            }
                        }
                        item["CategoryCode"] = value;

                        printDt.Rows.Add(item.ItemArray);

                        index++;
                        if (index == 7)
                        {
                            printDt.Rows.Add(item.ItemArray);
                            DataRow printDr = printDt.Rows[printDt.Rows.Count - 1];
                            printDr["Date"] = printDr["Date"] + "总积休";
                            printDr["DayOfWeek"] = "小时";
                            printDr["CategoryCode"] = printDr["SuperWorkHours"];
                            index = 0;
                        }
                    }
                }
            }
            var result = new { Rows = printDt };
            return JsonDate(result);
        }
    }
}

